#include "TicketBooking.h"
#include "./ui_TicketBooking.h"
#include <QThreadPool>
#include <QMetaObject>
TicketBooking::TicketBooking(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::TicketBooking)
{
    ui->setupUi(this);
}

TicketBooking::~TicketBooking()
{
    abort=true;
    QThreadPool::globalInstance()->waitForDone(10000);//等待线程池里面的线程执行完毕才返回
    delete ui;
}

void TicketBooking::run(){
    int id=number++;
    while(!abort){
        if(res>0){
            res--;//！核心步骤
            auto msg=QString("你的小助手正在%1正在帮小主努力抢票哟~\n").arg(id);
            QMetaObject::invokeMethod(ui->textBrowser,"insertPlainText",Q_ARG(QString,msg));
        }
        if(!isvip){
            QThread::msleep(1000);//延迟一秒种
        }

        else{
            QThread::msleep(500);
        }
    }
    qInfo()<<"finished";
}
void TicketBooking::on_startbtn_clicked()
{
    //开始抢票
    if(!isTicketGrabbing){
        isTicketGrabbing=true;
        ui->startbtn->setText("停止抢票");
        abort=false;
        ui->textBrowser->clear();
        number=1;
        for(int i=0;i<2;i++){
            QThreadPool::globalInstance()->start(std::bind(&TicketBooking::run,this));
        }
        elaspedtimer.start();

    }
    //停止抢票
    else{
        isTicketGrabbing=false;
        ui->startbtn->setText("开始抢票");
        abort=true;
    }
}


void TicketBooking::on_vipbtn_clicked()
{
    isvip=true;
}


void TicketBooking::on_textBrowser_textChanged()
{
    ui->textBrowser->ensureCursorVisible();
    //获取抢票时间（秒）
    qint64 t=elaspedtimer.elapsed()/1000;
    ui->displaytimerLab->setText(QString("小助手们已帮小主抢票%1小时%2分%3秒")
                                     .arg(t/60/60,2,10,QChar('0'))
                                     .arg(t/60%60,2,10,QChar('0'))
                                     .arg(t%60,2,10,QChar('0')));
}

